package pe.com.astech.web.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import pe.com.astech.web.bean.MaterialBean;
import pe.com.astech.web.bean.PerfilBean;
import pe.com.astech.web.dao.MaterialDao;
import pe.com.astech.web.exception.DBException;

@Repository
public class MaterialDaoImpl implements MaterialDao {

	private JdbcTemplate jdbcTemplate;
	
	private static final Log log = LogFactory.getLog(MaterialDaoImpl.class);

	@Autowired
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}
	
	@Override
	public List<MaterialBean> consultarMateriales(String cadenaTrazabilidad,
			String nombre){
		
		String query = "select m.id_material,m.nombre,m.stock,m.descripcion,m.tipo_material_ID,t.nombre as nombreTipoMaterial " +
						"from material m " +
						"inner join tipo_material t on t.id_tipo_material=m.tipo_material_ID " +
						"where m.nombre like :nombre ";
		
		List<MaterialBean> list = new ArrayList<MaterialBean>();
		log.info("query : " + query);
		MapSqlParameterSource parameters = new MapSqlParameterSource();
	 	parameters.addValue("nombre", "%"+nombre+"%");
	 	
	 	NamedParameterJdbcTemplate namedParameterJdbcTemplate= new NamedParameterJdbcTemplate(jdbcTemplate);
		List<Map<String, Object>> usrRows = namedParameterJdbcTemplate.queryForList(query,parameters);
			
			for (Map<String, Object> usrRow : usrRows) {
				
				MaterialBean materialBean = new MaterialBean();
				materialBean.setId_material(String.valueOf(usrRow.get("id_material")));
				materialBean.setNombre(String.valueOf(usrRow.get("nombre")));
				materialBean.setStock(String.valueOf(usrRow.get("stock")));
				materialBean.setDescripcion(String.valueOf(usrRow.get("descripcion")));
				materialBean.setTipo_material_id(String.valueOf(usrRow.get("tipo_material_ID")));
				materialBean.setNombre_tipo_material(String.valueOf(usrRow.get("nombreTipoMaterial")));
				
				list.add(materialBean);
			}
		return list;
	}

}
